package com.weizai.carshop.service.Impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.weizai.carshop.common.properties.MinioProperties;
import com.weizai.carshop.common.result.ResponseResult;
import com.weizai.carshop.mapper.ImageMapper;
import com.weizai.carshop.model.entiity.ImageEntity;
import com.weizai.carshop.service.UploadFileService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.util.UUID;


@Service
public class UploadFileServiceImpl extends ServiceImpl<ImageMapper, ImageEntity> implements UploadFileService {

    @Autowired
    private MinioProperties minIOConfigProperties;
    @Autowired
    private MinioClient minioClient;
    /**
     *  上传图片文件
     */
    @Override
    public ResponseResult uploadImgFile(MultipartFile multipartFile) {
        // 1.检查参数
        if (multipartFile == null || multipartFile.getSize()==0){
            return ResponseResult.errorResult(400, "上传文件不能为空");
        }
        // 2.上传图片到minIo中
        String fileName = UUID.randomUUID().toString().replace("-", "");
        // 获取文件后缀
        String originalFilename = multipartFile.getOriginalFilename();
        String returnUrl = minIOConfigProperties.getEndpoint()+"/"+minIOConfigProperties.getBucketName()+"/"+fileName+ originalFilename.substring(originalFilename.lastIndexOf("."));
        String URL = fileName+ originalFilename.substring(originalFilename.lastIndexOf("."));
        try{
             // 上传文件
             PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .bucket(minIOConfigProperties.getBucketName())
                    .object(URL)
                    .stream(multipartFile.getInputStream(), multipartFile.getSize(), -1)
                    .contentType(multipartFile.getContentType())
                    .build();
            minioClient.putObject(putObjectArgs);
            System.out.println("上传文件成功:"+ returnUrl);
            return ResponseResult.okResult(returnUrl);
        }catch (Exception e){
            return ResponseResult.errorResult(500, "上传文件失败");
        }
    }

}
